import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, logout, getUserInfo } from '@/api/auth'
import { getUserMenus } from '@/api/menu'
import { setToken, removeToken, getToken } from '@/utils/auth'

// 从localStorage获取菜单数据
const getMenuFromStorage = () => {
  try {
    const menuData = localStorage.getItem('user-menu-list')
    return menuData ? JSON.parse(menuData) : []
  } catch (error) {
    console.error('解析菜单数据失败:', error)
    return []
  }
}

// 保存菜单数据到localStorage
const saveMenuToStorage = (menuList) => {
  try {
    localStorage.setItem('user-menu-list', JSON.stringify(menuList))
  } catch (error) {
    console.error('保存菜单数据失败:', error)
  }
}

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken() || '')
  const userInfo = ref({})
  const roles = ref([])
  const permissions = ref([])
  const menuList = ref(getMenuFromStorage())

  // 登录
  const loginAction = async (loginForm) => {
    try {
      const { data } = await login(loginForm)
      const { token: userToken } = data
      token.value = userToken
      setToken(userToken)
      return Promise.resolve()
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      const { data } = await getUserInfo()
      userInfo.value = data.userInfo
      roles.value = data.roles
      permissions.value = data.permissions
      return Promise.resolve(data)
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 获取用户菜单
  const getMenuAction = async () => {
    try {
      const { data } = await getUserMenus()
      menuList.value = data || []
      // 保存到localStorage
      saveMenuToStorage(menuList.value)
      return Promise.resolve(data)
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 登出
  const logoutAction = async () => {
    try {
      await logout()
      token.value = ''
      userInfo.value = {}
      roles.value = []
      permissions.value = []
      menuList.value = []
      // 清除localStorage中的菜单数据
      localStorage.removeItem('user-menu-list')
      removeToken()
      return Promise.resolve()
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 重置状态
  const resetState = () => {
    token.value = ''
    userInfo.value = {}
    roles.value = []
    permissions.value = []
    menuList.value = []
    // 清除localStorage中的菜单数据
    localStorage.removeItem('user-menu-list')
    removeToken()
  }

  return {
    token,
    userInfo,
    roles,
    permissions,
    menuList,
    loginAction,
    getUserInfoAction,
    getMenuAction,
    logoutAction,
    resetState
  }
}) 